<template>
  <div class="search">
    <Card>
      <Row>
        <Form
          ref="editForm"
          :model="editForm"
          :rules="rules"
          style="width: 100%"
          :label-width="120"
        >
          <FormItem label="活动名称" prop="title">
            <Input
              v-model="editForm.title"
              placeholder="请输入活动名称"
              :maxlength="50"
              style="width: 40%"
            />
          </FormItem>
          <FormItem label="活动排序" prop="sort">
            <Input
              v-model="editForm.sort"
              type="number"
              placeholder="请输入活动排序"
              style="width: 40%"
            />
          </FormItem>
          <FormItem label="活动封面" prop="thumb">
            <Upload
              action
              type="drag"
              ref="upload"
              :max-size="2 * 1024"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              accept=".jpg, .jpeg, .bmp, .png"
              :format="['jpg', 'jpeg', 'bmp', 'png']"
              style="width: max-content; display: inline-block"
            >
              <img v-if="editForm.thumb" class="baseItem" :src="editForm.thumb" />
              <div v-else style="width: 150px; height: 150px; line-height: 150px">
                <Icon type="md-add" size="20" />
              </div>
            </Upload>
            <span style="margin-left: 20px; color: #aaa"
              >只能上传jpg/png/bmp文件，且不超过2MB</span
            >
          </FormItem>
          <FormItem label="报名时间" prop="rRange">
            <DatePicker
              type="datetimerange"
              v-model="editForm.rRange"
              :options="rOption"
              :editable="false"
              placeholder="请选择报名时间"
              format="yyyy-MM-dd HH:mm:ss"
              style="width: 40%"
            />
          </FormItem>
          <FormItem label="活动时间" prop="aRange">
            <DatePicker
              type="datetimerange"
              v-model="editForm.aRange"
              :options="aOption"
              :editable="false"
              placeholder="请选择活动时间"
              format="yyyy-MM-dd HH:mm:ss"
              style="width: 40%"
            />
          </FormItem>
          <FormItem label="活动详情" prop="content">
            <editor
              ref="editor"
              openXss
              style="width: 70%"
              v-model="editForm.content"
              :init="{ ...initEditor, height: '800px' }"
            />
          </FormItem>
          <FormItem label="报名人数上限" prop="num">
            <Input
              v-model="editForm.num"
              type="number"
              placeholder="请输入报名人数上限"
              style="width: 40%"
            />
          </FormItem>
          <div>
            <Button type="text" @click="toback">返回</Button>
            <Button type="primary" @click="submitForm">保存</Button>
          </div>
        </Form>
      </Row>
    </Card>
  </div>
</template>

<script>
import * as API_community from "@/api/community.js";
import Editor from "@tinymce/tinymce-vue";
import { initEditor } from "@/components/editor/config";

export default {
  name: "base-form",
  components: {
    editor: Editor,
  },
  data() {
    return {
      initEditor: initEditor,
      editForm: {
        // 表单
        id: null,
        title: null, // 活动名称
        sort: null, // 活动排序
        thumb: null, // 活动封面
        rRange: null, // 报名时间范围
        ready_stime: null, // 报名开始时间
        ready_time: null, // 报名结束时间
        aRange: null, // 活动时间范围
        act_stime: null, // 活动开始时间
        act_time: null, // 活动结束时间
        num: null, // 报名人数上限
        content: null, // 活动详情
        pusher: null, // 创建人
      },
      rules: {
        // 验证规则
        title: [{ required: true, message: "请输入活动名称" }],
        thumb: [{ required: true, message: "请上传活动封面" }],
        rRange: [{ required: true, message: "请选择报名时间" }],
        aRange: [{ required: true, message: "请选择活动时间" }],
        content: [{ required: true, message: "请输入活动详情" }],
        num: [
          { required: true, message: "请输入报名人数上限" },
          { pattern: /^[1-9]\d*$/, message: "请输入大于0的整数", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "请输入活动排序" },
          { pattern: /^[1-9]\d*$/, message: "请输入大于0的整数", trigger: "blur" },
        ],
      },
      // 报名日期限制
      rOption: {
        disabledDate: (date) => {
          let now = new Date().getTime();
          let range = this.editForm.aRange;
          let s = 0;
          if (range && range.length && range[0]) s = new Date(range[0]).getTime();
          return date && date.valueOf() < now || date.valueOf() >= s && s != 0;
        },
      },
      // 活动日期限制
      aOption: {
        disabledDate: (date) => {
          let now = new Date().getTime();
          let range = this.editForm.rRange;
          let s = 0;
          if (range && range.length && range[1]) s = new Date(range[1]).getTime();
          return date && date.valueOf() < now || date.valueOf() <= s;
        },
      },
    };
  },
  mounted() {
    let id = this.$route.query.id;
    this.init(id);
  },
  methods: {
    // 返回上级
    toback() {
      this.$store.commit("removeTag", "activity-form");
      localStorage.pageOpenedList = JSON.stringify(this.$store.state.app.pageOpenedList);
      this.$router.go(-1);
    },
    // 初始化表单
    init(id) {
      if (id) {
        API_community.activityDetail({ id }).then((res) => {
          if (res.code == 200) {
            Object.keys(this.editForm).map((i) => {
              this.editForm[i] = res.data[i];
            });
            let rstime, retime, astime, aetime;
            if (this.editForm.ready_stime)
              rstime = this.formatDate(this.editForm.ready_stime);
            if (this.editForm.ready_time)
              retime = this.formatDate(this.editForm.ready_time);
            if (this.editForm.act_stime)
              astime = this.formatDate(this.editForm.act_stime);
            if (this.editForm.act_time) aetime = this.formatDate(this.editForm.act_time);
            this.editForm.rRange = [rstime, retime];
            this.editForm.aRange = [astime, aetime];
          }
        });
      }
      this.$refs.editForm.resetFields();
    },
    // 时间格式转换
    formatDate(v) {
      return new Date(v * 1000).Format("yyyy-MM-dd hh:mm:ss");
    },
    // 自定义上传
    beforeUpload(file) {
      let typeList = [".jpg", ".jpeg", ".bmp", ".png"];
      if (!typeList.some((i) => file.name.lastIndexOf(i) != -1)) {
        this.$Message.warning("请检查上传文件格式");
        return;
      }
      if (file.size / 1024 > 2 * 1024) {
        this.$Message.warning("图片大小不能超过2MB");
        return;
      }
      const formData = new FormData();
      formData.append("file", file);
      API_community.postUpload(formData).then((res) => {
        if (res.success) {
          this.editForm.thumb = res.result;
        }
      });
      return false;
    },
    //提交
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          let user = JSON.parse(localStorage.getItem("userInfoManager"));
          let params = Object.assign({}, this.editForm);
          params.pusher = user.nickName; // 创建人名称
          if (params.rRange) {
            params.ready_stime = params.rRange[0].getTime() / 1000;
            params.ready_time = params.rRange[1].getTime() / 1000;
          }
          if (params.aRange) {
            params.act_stime = params.aRange[0].getTime() / 1000;
            params.act_time = params.aRange[1].getTime() / 1000;
          }
          delete params.rRange;
          delete params.aRange;
          if (params.id) {
            API_community.activityEdit(params).then((res) => {
              if (res.code == 200) {
                this.$Message.success(res.msg);
                this.toback();
              }
            });
          } else {
            API_community.activityAdd(params).then((res) => {
              if (res.code == 200) {
                this.$Message.success(res.msg);
                this.toback();
              }
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss">
.tox.tox-tinymce.tox-fullscreen {
  top: 110px !important;
  left: 190px !important;
  width: calc(100% - 202px) !important;
  height: calc(100% - 122px) !important;
}
.baseItem {
  display: inline-block;
  position: relative;
  height: 9.375rem;
  min-width: 9.375rem;
  margin-right: 0.625rem;
  .base-icon {
    position: absolute;
    top: 0.3125rem;
    color: #fff;
    font-size: 1.25rem;
    right: 5px;
    &:hover {
      cursor: pointer;
    }
  }
  &:hover {
    opacity: 0.9;
  }
  img {
    height: 100%;
  }
}
</style>
